package com.zlx.mall.biz.attribution.controller;


import com.zlx.mall.basic.common.exception.ExceptionWrapper;
import com.zlx.mall.basic.common.exception.IllegalRequestArgumentException;
import com.zlx.mall.basic.common.model.SystemParam;
import com.zlx.mall.basic.trace.MDCUtil;
import com.zlx.mall.basic.util.json.JacksonUtil;
import com.zlx.mall.basic.web.holder.RequestContextHolder;
import com.zlx.mall.basic.web.model.BaseRequest;
import com.zlx.mall.basic.web.model.BaseResponse;
import com.zlx.mall.biz.access.constant.AccessConstants;
import com.zlx.mall.biz.attribution.model.PointDataLine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author qingke
 **/
@Slf4j(topic = "attributionLogger")
@RestController
public class AttributionController {

    @RequestMapping(path = "/api/point/save/v1", method = {RequestMethod.POST})
    public BaseResponse save(BaseRequest baseRequest) {

        String systemParamContext = Optional
                .ofNullable(RequestContextHolder.getHeader(AccessConstants.HEADER_NAME_ACCESS_TOKEN))
                .filter(StringUtils::hasText)
                .orElseThrow(() -> new IllegalRequestArgumentException("System Data must not be null"));

        SystemParam systemParam = ExceptionWrapper.wrap(
                () -> JacksonUtil.toObject(systemParamContext, SystemParam.class),
                IllegalRequestArgumentException::new);

        PointDataLine line = new PointDataLine();
        line.setRemoteAddress(RequestContextHolder.getRemoteAddress());
        line.setTimestamp(System.currentTimeMillis());
        line.setTraceId(MDCUtil.getTraceId());
        line.setSystemParam(systemParam);
        line.setUserId(baseRequest.getUserId());
        line.setContent(RequestContextHolder.getContent());
        log.info("{}", JacksonUtil.toJsonString(line));
        return BaseResponse.success();
    }
}
